//
//  CodeTextField.swift
//  TTSDemo
//
//  Created by whale on 2022/7/14.
//

import UIKit


class CodeTextField: ICTextField {
    
    lazy var man = LoginMan()
    
    var hintText: String? {
        didSet {
            attributedPlaceholder = hintText?.text(font: font ?? .font(15), color: .placeholder)
        }
    }
    var phone: String?
    
    var timeCount = 60
    private var _timeCount: Int = 60 {
        didSet{
            if _timeCount <= 0 || _timeCount == 60 {
                rightItem.isSelected = false
            }else {
                rightItem.isSelected = true
                rightItem.setTitle("\(_timeCount)s", for: .selected)
                rightItem.setTitleColor(UIColor.placeholder, for: .selected)
            }
        }
    }
    
    var isRightTextClosure: ((Bool, String)->())?
    
    private lazy var disposeBag = DisposeBag()
    
    lazy var rightItem: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("获取验证码", for: .normal)
        btn.setTitleColor(UIColor._blue, for: .normal)
        btn.addTarget(self, action: #selector(rightItemClick), for: .touchUpInside)
        return btn
    }()
    
    
    required convenience init() {
        self.init(frame: .zero)

        hintText = "请输入验证码"
        rightViewWidth = 100.adapter
        rightViewMode = .always
        rightView = rightItem
        keyboardType = .numberPad
        insets = UIEdgeInsets(left: 10.adapter)
        self.rx.text.orEmpty.changed.subscribe { [weak self] str in
            self?.textChange(str)
        }.disposed(by: disposeBag)
    }
    
    @objc private func rightItemClick() {
        if phone == nil || phone?.count == 0 {
            HUD.toast("请输入手机号码")
            return
        }
        if rightItem.isSelected {
            return
        }
//        man.sms(self.phone) { [weak self] in
//            self?.smsEvent()
//        }
        smsEvent()
    }
    
    private func smsEvent() {
        let obsTimer = Observable<Int>.interval(.seconds(1), scheduler: MainScheduler.instance).subscribe { n in
                self._timeCount = self.timeCount - (n.element ?? 0) - 1
        }
        
        DispatchQueue.main.asyncAfter(deadline: .now() + TimeInterval(timeCount)) {
            obsTimer.dispose()
        }
    
        obsTimer.disposed(by: disposeBag)
    }
    
    private func textChange(_ str: String?) {

        isRightTextClosure?(str != nil && str?.count != 0, str ?? "")
    }

}
